import Cookies from 'js-cookie'
import _ from 'lodash'


export function useMorghulisCookies() {

    function get(path: string): any {
        const key = getKeyFromPath(path)
        const value = getJsonFromCookies(key)
        const _path = path.substring(path.indexOf('.') + 1)
        return key === path ? value : _.get(value, _path)
    }

    function set(path: string, value?: any): void {
        const key = getKeyFromPath(path)
        if (value == null) remove(key)
        else if (key === path) Cookies.set(key, JSON.stringify(value))
        else {
            const oldValue = getJsonFromCookies(key) || {}
            const newValue = _.set(oldValue, path, value);
            Cookies.set(key, JSON.stringify(newValue))
        }
    }

    function load(key: string, value?: any): any {
        const val = get(key)
        if (val == null) set(key, value)
        return get(key)
    }

    function remove(path: string): void {
        const key = getKeyFromPath(path)
        if (key === path) Cookies.remove(key)
        else {
            const value = getJsonFromCookies(key)
            const _path = path.substring(path.indexOf('.') + 1)
            _.unset(value, _path)
            set(key, value)
        }
    }

    return {get, set, remove, load}
}

function getKeyFromPath(path: string) {
    const ks = path.split('.')
    let key = ks[0]
    let index = key.indexOf('[')
    return index === -1 ? key : key.substring(0, index)
}

function getJsonFromCookies(key: string) {
    const value = Cookies.get(key)
    if (value == null) return null
    try {
        return JSON.parse(value)
    } catch (e) {
        return value
    }
}